package cn.com.thingo.hyintelligent.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.hikvision.netsdk.PTZCommand;
import com.suke.widget.SwitchButton;
import com.th.opensdk.openapi.SecurityInfo;
import com.th.opensdk.openapi.THOpenSDK;
import com.videogo.constant.Constant;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.exception.ExtraException;
import com.videogo.exception.InnerException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.util.Base64;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LocalInfo;
import com.videogo.util.LocalValidate;
import com.videogo.util.LogUtil;
import com.videogo.util.MD5Util;
import com.videogo.util.MediaScanner;
import com.videogo.util.SDCardUtil;
import com.videogo.util.Utils;
import com.videogo.widget.RingView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.app.EzHttpConstants;
import cn.com.thingo.hyintelligent.base.RootFragment;
import cn.com.thingo.hyintelligent.base.contract.MonitorContract;
import cn.com.thingo.hyintelligent.model.bean.EzAccountBean;
import cn.com.thingo.hyintelligent.model.bean.GetEzTokenBean;
import cn.com.thingo.hyintelligent.model.bean.UserBean;
import cn.com.thingo.hyintelligent.model.db.EzMonitorAddEntity;
import cn.com.thingo.hyintelligent.model.db.EzMonitorRecEntity;
import cn.com.thingo.hyintelligent.model.db.UserInfo;
import cn.com.thingo.hyintelligent.presenter.MonitorPresenter;
import cn.com.thingo.hyintelligent.ui.activity.EzDeviceFullScreenActivity;
import cn.com.thingo.hyintelligent.ui.activity.EzDeviceManagerActivity;
import cn.com.thingo.hyintelligent.ui.activity.EzWifiNetConfigActivity;
import cn.com.thingo.hyintelligent.ui.activity.SearchEzDeviceActivity;
import cn.com.thingo.hyintelligent.ui.adapter.MonitorRecAdapter;
import cn.com.thingo.hyintelligent.util.AudioPlayUtil;
import cn.com.thingo.hyintelligent.util.EZUtils;
import cn.com.thingo.hyintelligent.util.SPUtils;
import cn.com.thingo.hyintelligent.util.ToastUtil;
import cn.com.thingo.hyintelligent.util.VerifyCodeInput;
import cn.com.thingo.hyintelligent.widget.PlayerLoadingTextView;

import static cn.com.thingo.hyintelligent.app.EzHttpConstants.ADD_DEVICE_SUCCESS_ACTION;
import static com.tencent.bugly.crashreport.crash.c.m;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MonitorFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MonitorFragment extends RootFragment<MonitorPresenter> implements MonitorContract.View, SwitchButton.OnCheckedChangeListener {
    @BindView(R.id.tv_ez_manager)
    TextView mTvEzManager;
    @BindView(R.id.ll_ez_manager)
    LinearLayout llEzManager;
    @BindView(R.id.rec_player)
    RecyclerView mRecyclerView;
    @BindView(R.id.in_player)
    View mView;
    @BindView(R.id.view_monitor)
    View mMonitorView;
    @BindView(R.id.iv_rotate)
    ImageView mRotateImage;
    @BindView(R.id.iv_first)
    ImageView mIvFirst;
    @BindView(R.id.iv_microphone)
    ImageView mIvMicrophone;
    @BindView(R.id.iv_camera)
    ImageView mIvCamera;
    @BindView(R.id.iv_volume)
    ImageView mIvVolume;
    @BindView(R.id.iv_full_screen)
    ImageView mIvFullScreen;
    @BindView(R.id.monitor_defense_setting)
    SwitchButton sbDefenseSetting;
    private static final int SPAN_COUNT = 2;
    private BroadcastReceiver mAddSuccessReceiver;
    private String deviceType = "";
    private MonitorRecAdapter mMonitorRecAdapter;
    private List<MultiItemEntity> mEntityList;
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private PopupMenu mPopupMenu;
    /**
     * 序列号结果变量
     */
    private String mSerialNoStr = null;
    private String mSerialVeryCodeStr = null;
    /**
     * 本地数据合法性检测变量
     */
    private LocalValidate mLocalValidate = null;
    private static final String TAG = MonitorFragment.class.getSimpleName();// 打印标识
    private AudioPlayUtil mAudioPlayUtil;
    public static final String BROADCAST_FIRST = "send_first_player";
    // 对讲模式
    private boolean mIsOnTalk = false;
    private PopupWindow mTalkPopupWindow = null;
    private RingView mTalkRingView = null;
    private Button mTalkBackControlBtn = null;
    private LocalInfo mLocalInfo;
    private int mEzAdapterPosition;
    private UserInfo mUserInfo;
    private boolean isHide;
    private static final int MAX_SIZE = 4;
    private EZConstants.EZPTZCommand mEZPTZCommand;

    public MonitorFragment() {
        // Required empty public constructor
    }

    public static MonitorFragment newInstance() {
        return new MonitorFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_monitor;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }


    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        // 获取配置信息操作对象
        mUserInfo = UserInfo.getInstance();
        mLocalInfo = LocalInfo.getInstance();
        mAudioPlayUtil = AudioPlayUtil.getInstance((Application) mContext.getApplicationContext());
//        mTvEzManager.setText(Html.fromHtml("<u>" + getString(R.string.monitor_manager) + "</u>"));
//        mTvEzManager.setOnClickListener(this);
        sbDefenseSetting.setOnCheckedChangeListener(this);
        mAddSuccessReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                assert action != null;
                switch (action) {
                    case ADD_DEVICE_SUCCESS_ACTION:
                    case EzDeviceManagerActivity.DELETE_DEVICE_SUCCESS_ACTION:
                        mPresenter.getDeviceInfoList(mUserInfo.getRamAccessToken());
                        break;
                }

            }
        };

        if (mLocalInfo.isSoundOpen()) {
            mIvVolume.setImageResource(R.mipmap.player_volume_open);
        } else {
            mIvVolume.setImageResource(R.mipmap.player_volume_close);
        }
        IntentFilter addFilter = new IntentFilter();

        addFilter.addAction(ADD_DEVICE_SUCCESS_ACTION);
        addFilter.addAction(EzDeviceManagerActivity.DELETE_DEVICE_SUCCESS_ACTION);
        mContext.registerReceiver(mAddSuccessReceiver, new IntentFilter(addFilter));
        showDevice();
        if (mUserInfo.getRamAccessToken() != null) {
            mPresenter.getDeviceInfoList(mUserInfo.getRamAccessToken());
            mView.setVisibility(View.VISIBLE);
        }
        THOpenSDK instance = THOpenSDK.getInstance();
        if (instance != null) {
            SecurityInfo security = instance.getSecurity();
            if (security != null) {
                boolean arming = security.isArming();
                sbDefenseSetting.setChecked(arming);
            }
        }
    }


    private void showDevice() {
        mEntityList = new ArrayList<>();
        for (int i = 0; i < MAX_SIZE; i++) {
            EzMonitorAddEntity addEntity = new EzMonitorAddEntity();
            mEntityList.add(addEntity);
        }
        mMonitorRecAdapter = new MonitorRecAdapter(mEntityList);

        GridLayoutManager manager = new GridLayoutManager(mContext, SPAN_COUNT);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mMonitorRecAdapter);
        mMonitorRecAdapter.setHandlerCallback(new MonitorRecAdapter.HandlerCallback() {
            @Override
            public Handler callback(final EzMonitorRecEntity entity, View view) {
                return new PlayerHandler(entity, view);
            }
        });
        mMonitorRecAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, final View view, final int position) {
                int viewType = adapter.getItemViewType(position);
                mEzAdapterPosition = position;
                switch (viewType) {
                    case MonitorRecAdapter.TYPE_DATA:
                        final ImageView ivPlay = view.findViewById(R.id.realplay_play_iv);
                        if (ivPlay.getVisibility() == View.VISIBLE) {
                            final EzMonitorRecEntity ezMonitorRecEntity = (EzMonitorRecEntity) adapter.getItem(position);
                            final SurfaceView surfaceView = view.findViewById(R.id.realplay_sv);
                            final TextView tvTip = view.findViewById(R.id.realplay_tip_tv);
                            final PlayerLoadingTextView viewLoading = view.findViewById(R.id.realplay_loading);
                            assert ezMonitorRecEntity != null;
                            final EZPlayer ezPlayer = ezMonitorRecEntity.getEZPlayer();
                            VerifyCodeInput.VerifyCodeInputDialog(mContext, new VerifyCodeInput.VerifyCodeInputListener() {
                                @Override
                                public void onInputVerifyCode(String verifyCode) {
                                    ezPlayer.setPlayVerifyCode(verifyCode);
                                    ezPlayer.setSurfaceHold(surfaceView.getHolder());
                                    ezMonitorRecEntity.setVerifyCode(verifyCode);
                                    ezPlayer.setHandler(new PlayerHandler(ezMonitorRecEntity, view));
                                    ezPlayer.startRealPlay();
                                    tvTip.setVisibility(View.GONE);
                                    ivPlay.setVisibility(View.GONE);
                                    viewLoading.setVisibility(View.VISIBLE);
                                }
                            }).show();
                        }
                        break;
                    case MonitorRecAdapter.TYPE_ADD:
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2);
                        } else {
                            showAddDeviceDialog();
                        }
                        break;
                }
            }
        });
    }

    class PopmenuListener implements PopupMenu.OnMenuItemClickListener {
        private EzMonitorRecEntity mEzMonitorRecEntity;

        public PopmenuListener(EzMonitorRecEntity ezMonitorRecEntity) {
            mEzMonitorRecEntity = ezMonitorRecEntity;
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.up:
                    ptzControl(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTART, 0);
                    break;
                case R.id.down:
                    ptzControl(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTART, 0);
                    break;
                case R.id.left:
                    ptzControl(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTART, 0);
                    break;
                case R.id.right:
                    ptzControl(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTART, 0);
                    break;
                case R.id.far:
                    ptzControl(EZConstants.EZPTZCommand.EZPTZCommandZoomOut, EZConstants.EZPTZAction.EZPTZActionSTART, 0);
                    break;
                case R.id.nearly:
                    ptzControl(EZConstants.EZPTZCommand.EZPTZCommandZoomIn, EZConstants.EZPTZAction.EZPTZActionSTART, 0);
                    break;
                case R.id.stop:
                    if (mEZPTZCommand != null) {
                        ptzControl(mEZPTZCommand, EZConstants.EZPTZAction.EZPTZActionSTOP, 0);
                    }
                    break;
            }
            return false;
        }

        private void ptzControl(final EZConstants.EZPTZCommand command, final EZConstants.EZPTZAction action, final int speed) {
            if (action == EZConstants.EZPTZAction.EZPTZActionSTART && mEZPTZCommand != null) {
                ToastUtil.show("请先点击停止选项");
                return;
            }
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        EZOpenSDK.getInstance().controlPTZ(mEzMonitorRecEntity.getEZDeviceInfo().getDeviceSerial(), 1, command, action, speed);
                        if (action == EZConstants.EZPTZAction.EZPTZActionSTOP) {
                            mEZPTZCommand = null;
                        } else {
                            mEZPTZCommand = command;
                        }
                    } catch (final BaseException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.show(e.getMessage());
                            }
                        });
                    }
                }
            });
        }
    }


    class PlayerHandler extends Handler {
        private EzMonitorRecEntity mEntity;
        private View mView;

        PlayerHandler(EzMonitorRecEntity entity, View view) {
            mEntity = entity;
            mView = view;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ImageView ivPlay = mView.findViewById(R.id.realplay_play_iv);
            TextView tvTip = mView.findViewById(R.id.realplay_tip_tv);
            PlayerLoadingTextView viewLoading = mView.findViewById(R.id.realplay_loading);
            switch (msg.what) {
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                    SPUtils.newInstance().put(mEntity.getEZDeviceInfo().getDeviceSerial(), mEntity.getVerifyCode());
                    mEntity.setPlay(true);
                    tvTip.setVisibility(View.GONE);
                    ivPlay.setVisibility(View.GONE);
                    viewLoading.setVisibility(View.GONE);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                    mEntity.setPlay(false);
                    mEntity.setVerifyCode(null);
                    tvTip.setVisibility(View.GONE);
                    ivPlay.setVisibility(View.VISIBLE);
                    viewLoading.setVisibility(View.GONE);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_SUCCESS:
                    openTalkPopupWindow(true, mEntity);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_STOP:
                    handleVoiceTalkStoped(false, mEntity);
                    break;
                case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_FAIL:
                    ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                    handleVoiceTalkFailed(errorInfo, mEntity);
                    break;
            }
        }
    }

    private void handleVoiceTalkFailed(ErrorInfo errorInfo, EzMonitorRecEntity entity) {
        LogUtil.debugLog(TAG, "Talkback failed. " + errorInfo.toString());

        closeTalkPopupWindow(true, false, entity);

        switch (errorInfo.errorCode) {
            case ErrorCode.ERROR_TRANSF_DEVICE_TALKING:
                Utils.showToast(mContext, R.string.realplay_play_talkback_fail_ison);
                break;
            case ErrorCode.ERROR_TRANSF_DEVICE_PRIVACYON:
                Utils.showToast(mContext, R.string.realplay_play_talkback_fail_privacy);
                break;
            case ErrorCode.ERROR_TRANSF_DEVICE_OFFLINE:
                Utils.showToast(mContext, R.string.realplay_fail_device_not_exist);
                break;
            case ErrorCode.ERROR_TTS_MSG_REQ_TIMEOUT:
            case ErrorCode.ERROR_TTS_MSG_SVR_HANDLE_TIMEOUT:
            case ErrorCode.ERROR_TTS_WAIT_TIMEOUT:
            case ErrorCode.ERROR_TTS_HNADLE_TIMEOUT:
                Utils.showToast(mContext, R.string.realplay_play_talkback_request_timeout, errorInfo.errorCode);
                break;
            case ErrorCode.ERROR_CAS_AUDIO_SOCKET_ERROR:
            case ErrorCode.ERROR_CAS_AUDIO_RECV_ERROR:
            case ErrorCode.ERROR_CAS_AUDIO_SEND_ERROR:
                Utils.showToast(mContext, R.string.realplay_play_talkback_network_exception, errorInfo.errorCode);
                break;
            default:
                Utils.showToast(mContext, R.string.realplay_play_talkback_fail, errorInfo.errorCode);
                break;
        }
    }

    private void showScan() {
        QrConfig qrConfig = new QrConfig.Builder()
                .setShowDes(false)
                .setShowLight(true)
                .setShowTitle(true)
                .setShowAlbum(true)
                .setCornerColor(Color.WHITE)
                .setLineColor(Color.WHITE)
                .setLineSpeed(QrConfig.LINE_MEDIUM)
                .setScanType(QrConfig.TYPE_QRCODE)
                .setScanViewType(QrConfig.SCANVIEW_TYPE_QRCODE)
                .setPlaySound(true)
                .setNeedCrop(true)
                .setIsOnlyCenter(true)
                .setShowTitle(false)
                .create();
        QrManager.getInstance().init(qrConfig).startScan(getActivity(), new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(String resultString) {
                // 关注二维码名片地址
                // 例如：https://test.shipin7.com/h5/qrcode/intro?
                if (resultString.startsWith("https://") && resultString.contains("h5/qrcode/intro")) {
//            HikStat.onEvent(CaptureActivity.this, HikAction.ACTION_QRCODE_focus);
/*            Intent intent = new Intent(this, FollowActivity.class);
            intent.putExtra(IntentConsts.EXTRA_URL, resultString);
            startActivityForResult(intent, REQUEST_CODE_CLOUD);
*/
                    // 设备二维码名片
                } else if (resultString.startsWith("http://") && resultString.contains("smart.jd.com")) {
                    mSerialNoStr = "";
                    mSerialVeryCodeStr = "";
                    deviceType = "";
                    try {
                        String deviceInfoMarker = "$$$";
                        String contentMarker = "f=";
                        resultString = URLDecoder.decode(resultString, "UTF-8");
                        // 验证url有效性 f=打头的为 需要的内容
                        int contentIndex = resultString.indexOf(contentMarker);
                        if (contentIndex < 0) {
                            mSerialNoStr = resultString;
                            isValidate();
                            return;
                        }
                        contentIndex += contentMarker.length();
                        resultString = new String(Base64.decode(resultString.substring(contentIndex).trim()));
                        int index = resultString.indexOf(deviceInfoMarker);
                        // 二次判断有效性 $$$打头的为萤石信息
                        if (index < 0) {
                            mSerialNoStr = resultString;
                            isValidate();
                            return;
                        }
                        index += deviceInfoMarker.length();
                        resultString = resultString.substring(index);
                        String[] infos = resultString.split("\r\n");
                        if (infos.length >= 2) {
                            mSerialNoStr = infos[1];
                        }
                        if (infos.length >= 3) {
                            mSerialVeryCodeStr = infos[2];
                        }
                        if (infos.length >= 4) {
                            deviceType = infos[3];
                        }
                        isValidate();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    // TODO 判断是否为探测器 1.5个字段 2.最后一个字段T或者K打头 且长度为4
                    if (goAddProbe(resultString)) {
                        return;
                    }
                    // 初始化数据
                    mSerialNoStr = "";
                    mSerialVeryCodeStr = "";
                    deviceType = "";
                    LogUtil.errorLog(TAG, resultString);
                    // CS-F1-1WPFR
                    // CS-A1-1WPFR
                    // CS-C1-1FPFR
                    // resultString = "www.xxx.com\n456654855\nABCDEF\nCS-C3-21PPFR\n";
                    // 字符集合
                    String[] newlineCharacterSet = {
                            "\n\r", "\r\n", "\r", "\n"};
                    String stringOrigin = resultString;
                    // 寻找第一次出现的位置
                    int a = -1;
                    int firstLength = 1;
                    for (String string : newlineCharacterSet) {
                        if (a == -1) {
                            a = resultString.indexOf(string);
                            if (a > stringOrigin.length() - 3) {
                                a = -1;
                            }
                            if (a != -1) {
                                firstLength = string.length();
                            }
                        }
                    }

                    // 扣去第一次出现回车的字符串后，剩余的是第二行以及以后的
                    if (a != -1) {
                        resultString = resultString.substring(a + firstLength);
                    }
                    // 寻找最后一次出现的位置
                    int b = -1;
                    for (String string : newlineCharacterSet) {
                        if (b == -1) {
                            b = resultString.indexOf(string);
                            if (b != -1) {
                                mSerialNoStr = resultString.substring(0, b);
                                firstLength = string.length();
                            }
                        }
                    }

                    // 寻找遗失的验证码阶段
                    if (mSerialNoStr != null && b != -1 && (b + firstLength) <= resultString.length()) {
                        resultString = resultString.substring(b + firstLength);
                    }

                    // 再次寻找回车键最后一次出现的位置
                    int c = -1;
                    for (String string : newlineCharacterSet) {
                        if (c == -1) {
                            c = resultString.indexOf(string);
                            if (c != -1) {
                                mSerialVeryCodeStr = resultString.substring(0, c);
                            }
                        }
                    }

                    // 寻找CS-C2-21WPFR 判断是否支持wifi
                    if (mSerialNoStr != null && c != -1 && (c + firstLength) <= resultString.length()) {
                        resultString = resultString.substring(c + firstLength);
                    }
                    if (resultString != null && resultString.length() > 0) {
                        deviceType = resultString;
                    }

                    if (b == -1) {
                        mSerialNoStr = resultString;
                    }

                    if (mSerialNoStr == null) {
                        mSerialNoStr = stringOrigin;
                    }
                    LogUtil.debugLog(TAG, "mSerialNoStr = " + mSerialNoStr + ",mSerialVeryCodeStr = " + mSerialVeryCodeStr
                            + ",deviceType = " + deviceType);
                    // 判断是不是9位
                    isValidate();
                }
                // else {
                // 传感器添加 暂不实现
                // 网页/R1登录 暂不实现
                // 无法识别
                // handleLocalValidateSerialNoFail(ExtraException.SERIALNO_IS_ILLEGAL);
                // }
            }
        });
    }

    private void showAddDeviceDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        final String[] itemAlert = {getString(R.string.ez_pop_scan), getString(R.string.ez_pop_write)};
        builder.setTitle(R.string.select_add_way).setItems(itemAlert, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        showScan();
                        break;
                    case 1:
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", 0);
                        Intent intent = new Intent(mContext, SearchEzDeviceActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        }).setNegativeButton(android.R.string.cancel, null).show();
//                    EzBottomPopwindow ezBottomPopwindow = new EzBottomPopwindow(mContext);
//                    ezBottomPopwindow.setOnEzBottomPopClickListener(new OnEzBottomPopClickListener() {
//                        @Override
//                        public void OnEzAddScanClick(View view) {
//                            showScan();
//                        }
//
//                        @Override
//                        public void OnEzAddWriteClick(View view) {
//                            Bundle bundle = new Bundle();
//                            bundle.putInt("type", 0);
//                            Intent intent = new Intent(mContext, SearchEzDeviceActivity.class);
//                            intent.putExtras(bundle);
//                            startActivity(intent);
//                        }
//                    });
//                    ezBottomPopwindow.showAtLocation(mMonitorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @OnClick({R.id.iv_rotate, R.id.iv_first, R.id.iv_microphone, R.id.iv_camera, R.id.iv_volume, R.id.iv_full_screen, R.id.iv_more})
    void onPlayerBottomClick(View v) {
        MultiItemEntity entity = mMonitorRecAdapter.getItem(mEzAdapterPosition);
        if (entity.getItemType() == MonitorRecAdapter.TYPE_ADD) {
            return;
        }
        if (entity.getItemType() == MonitorRecAdapter.TYPE_DATA) {
            final EzMonitorRecEntity ezMonitorRecEntity = (EzMonitorRecEntity) entity;
            if (ezMonitorRecEntity.isPlay()) {
                Intent intent;
                Bundle bundle;
                switch (v.getId()) {
                    case R.id.iv_rotate:

                        executorService.execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    EZDeviceInfo info = ezMonitorRecEntity.getEZDeviceInfo();
                                    EZOpenSDK.getInstance().controlVideoFlip(info.getDeviceSerial(), info.getCameraInfoList().get(0).getCameraNo(), EZConstants.EZPTZDisplayCommand.EZPTZDisplayCommandFlip);
                                } catch (BaseException e) {
                                    e.printStackTrace();
                                }
                            }
                        });


                        break;
                    case R.id.iv_first:
                        intent = new Intent();
                        intent.setAction(BROADCAST_FIRST);
                        bundle = new Bundle();
                        bundle.putParcelable(BROADCAST_FIRST, ezMonitorRecEntity.getEZDeviceInfo());
                        intent.putExtras(bundle);
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
                        break;
                    case R.id.iv_microphone:
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
                        } else {
                            startVoiceTalk(ezMonitorRecEntity);
                        }
                        break;
                    case R.id.iv_camera:
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
                        } else {
                            onCapturePicBtnClick(ezMonitorRecEntity);
                        }

                        break;
                    case R.id.iv_volume:
                        onSoundBtnClick();
                        break;
                    case R.id.iv_full_screen:
                        intent = new Intent(mContext, EzDeviceFullScreenActivity.class);
                        bundle = new Bundle();
                        bundle.putString("deviceSerial", ezMonitorRecEntity.getEZDeviceInfo().getDeviceSerial());
                        bundle.putString("name", ezMonitorRecEntity.getEZDeviceInfo().getDeviceName());
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case R.id.iv_more:
                        if (mPopupMenu == null) {
                            mPopupMenu = new PopupMenu(mContext, v);
                            MenuInflater menuInflater = mPopupMenu.getMenuInflater();
                            menuInflater.inflate(R.menu.popmenu_player, mPopupMenu.getMenu());
                            mPopupMenu.setOnMenuItemClickListener(new PopmenuListener(ezMonitorRecEntity));
                        }
                        mPopupMenu.show();
                        break;
                    default:
                        break;

                }
            }
        }
    }

    @OnClick({R.id.ll_ez_manager})
    void onOtherClick(View view) {
        switch (view.getId()) {
            case R.id.ll_ez_manager:
                startActivity(new Intent(getActivity(), EzDeviceManagerActivity.class));
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            ToastUtil.show("权限已打开");
        } else {
            switch (requestCode) {
                case 1:
                    ToastUtil.show("请在设置中添加录音权限");
                case 2:
                    ToastUtil.show("请在设置中添加位置权限");
                    break;
                case 3:
                    ToastUtil.show("请在设置中添加存储权限");
                    break;
            }
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHide = hidden;

        if (mMonitorRecAdapter != null) {
            List<MultiItemEntity> list = mMonitorRecAdapter.getData();
            if (hidden) {
                for (int i = 0; i < list.size(); i++) {
                    MultiItemEntity multiItemEntity = list.get(i);
                    if (multiItemEntity.getItemType() == MonitorRecAdapter.TYPE_DATA) {
                        EzMonitorRecEntity ezMonitorRecEntity = (EzMonitorRecEntity) multiItemEntity;
                        if (!ezMonitorRecEntity.isPlay()) {
                            continue;
                        }
                        ezMonitorRecEntity.getEZPlayer().stopRealPlay();
                        SurfaceView surfaceView = (SurfaceView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_sv);
                        surfaceView.setVisibility(View.GONE);
                    }

                }
            } else {
                mEzAdapterPosition = 0;
                for (int i = 0; i < list.size(); i++) {
                    MultiItemEntity multiItemEntity = list.get(i);
                    if (multiItemEntity.getItemType() == MonitorRecAdapter.TYPE_DATA) {
                        EzMonitorRecEntity ezMonitorRecEntity = (EzMonitorRecEntity) multiItemEntity;
                        if (!ezMonitorRecEntity.isPlay()) {
                            continue;
                        }
                        PlayerLoadingTextView playerLoadingTextView = (PlayerLoadingTextView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_loading);
                        playerLoadingTextView.setVisibility(View.VISIBLE);
                        SurfaceView surfaceView = (SurfaceView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_sv);
                        ezMonitorRecEntity.getEZPlayer().setSurfaceHold(surfaceView.getHolder());
                        ezMonitorRecEntity.getEZPlayer().startRealPlay();
                        surfaceView.setVisibility(View.VISIBLE);
                    }

                }

            }
        }
    }

    private void onSoundBtnClick() {
        if (mLocalInfo.isSoundOpen()) {
            changeSound(false);
            mLocalInfo.setSoundOpen(false);
            mIvVolume.setImageResource(R.mipmap.player_volume_close);
        } else {
            changeSound(true);
            mLocalInfo.setSoundOpen(true);
            mIvVolume.setImageResource(R.mipmap.player_volume_open);

        }

    }

    private void changeSound(boolean isOpen) {
        List<MultiItemEntity> multiItemEntities = mMonitorRecAdapter.getData();
        for (MultiItemEntity e :
                multiItemEntities) {
            if (e instanceof EzMonitorRecEntity) {
                EZPlayer ezPlayer = ((EzMonitorRecEntity) e).getEZPlayer();
                if (ezPlayer == null) {
                    return;
                }
                if (isOpen) {
                    ezPlayer.openSound();
                } else {
                    ezPlayer.closeSound();
                }
            }
        }
    }


    /**
     * 打开对讲控制窗口
     *
     * @see
     * @since V1.8.3
     */
    private void openTalkPopupWindow(boolean showAnimation, final EzMonitorRecEntity entity) {
        if (!entity.isPlay()) {
            return;
        }
        closeTalkPopupWindow(false, false, entity);
        LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ViewGroup layoutView = (ViewGroup) layoutInflater.inflate(R.layout.realplay_talkback_wnd, null, true);
        layoutView.setFocusable(true);
        layoutView.setFocusableInTouchMode(true);
        layoutView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_BACK) {
                    LogUtil.infoLog(TAG, "KEYCODE_BACK DOWN");
                    closeTalkPopupWindow(true, false, entity);
                }
                return false;
            }
        });


        ImageButton talkbackCloseBtn = (ImageButton) layoutView.findViewById(R.id.talkback_close_btn);
        talkbackCloseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeTalkPopupWindow(true, false, entity);
            }
        });
        mTalkRingView = (RingView) layoutView.findViewById(R.id.talkback_rv);
        mTalkBackControlBtn = (Button) layoutView.findViewById(R.id.talkback_control_btn);
        mTalkBackControlBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        switch (v.getId()) {
                            case R.id.talkback_control_btn:
                                mTalkRingView.setVisibility(View.VISIBLE);
                                entity.getEZPlayer().setVoiceTalkStatus(true);
                                break;
                            default:
                                break;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        switch (v.getId()) {
                            case R.id.talkback_control_btn:
                                entity.getEZPlayer().setVoiceTalkStatus(false);
                                mTalkRingView.setVisibility(View.GONE);
                                break;

                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        if (entity.getEZDeviceInfo().isSupportTalk() == EZConstants.EZTalkbackCapability.EZTalkbackFullDuplex) {
            mTalkRingView.setVisibility(View.VISIBLE);
            mTalkBackControlBtn.setEnabled(false);
            mTalkBackControlBtn.setText(R.string.talking);
        }


        mTalkPopupWindow = new PopupWindow(layoutView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        // mTalkPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        if (showAnimation) {
            mTalkPopupWindow.setAnimationStyle(R.style.PopAnimBottom);
        }
        mTalkPopupWindow.setFocusable(false);
        mTalkPopupWindow.setOutsideTouchable(false);
//        mTalkPopupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        mTalkPopupWindow.showAsDropDown(mMonitorView);
        // mTalkPopupWindow.setOnDismissListener(new OnDismissListener() {
        //
        // @Override
        // public void onDismiss() {
        // LogUtil.infoLog(TAG, "KEYCODE_BACK DOWN");
        // mTalkPopupWindow = null;
        // closeTalkPopupWindow();
        // }
        // });
        mTalkPopupWindow.update();
        mTalkRingView.post(new Runnable() {
            @Override
            public void run() {
                if (mTalkRingView != null) {
                    mTalkRingView.setMinRadiusAndDistance(mTalkBackControlBtn.getHeight() / 2f,
                            Utils.dip2px(mContext, 22));
                }
            }
        });
    }

    private void closeTalkPopupWindow(boolean stopTalk, boolean startAnim, EzMonitorRecEntity entity) {
        if (mTalkPopupWindow != null) {
            LogUtil.infoLog(TAG, "closeTalkPopupWindow");
            dismissPopWindow(mTalkPopupWindow);
            mTalkPopupWindow = null;
        }
        mTalkRingView = null;
        if (stopTalk)
            stopVoiceTalk(startAnim, entity);
    }

    /**
     * 停止对讲
     *
     * @see
     * @since V2.0
     */
    private void stopVoiceTalk(boolean startAnim, EzMonitorRecEntity entity) {
        if (!entity.isPlay()) {
            return;
        }
        LogUtil.debugLog(TAG, "stopVoiceTalk");

        entity.getEZPlayer().stopVoiceTalk();
        handleVoiceTalkStoped(startAnim, entity);
    }

    private void handleVoiceTalkStoped(boolean startAnim, EzMonitorRecEntity entity) {
        if (mIsOnTalk) {
            mIsOnTalk = false;
        }

        if (entity.isPlay()) {
            if (LocalInfo.getInstance().isSoundOpen()) {
                entity.getEZPlayer().openSound();
                mIvVolume.setImageResource(R.mipmap.player_volume_open);
            } else {
                entity.getEZPlayer().closeSound();
                mIvVolume.setImageResource(R.mipmap.player_volume_close);
            }
        }
    }

    private void dismissPopWindow(PopupWindow popupWindow) {
        if (popupWindow != null && !((Activity) mContext).isFinishing()) {
            try {
                popupWindow.dismiss();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    /**
     * 设备对讲
     *
     * @see
     * @since V2.0
     */
    private void startVoiceTalk(EzMonitorRecEntity ezMonitorRecEntity) {
        LogUtil.debugLog(TAG, "startVoiceTalk");
        switch (ezMonitorRecEntity.getEZDeviceInfo().isSupportTalk()) {
            case EZTalkbackNoSupport:
                ToastUtil.show(R.string.no_support_talk);
                break;
            case EZTalkbackFullDuplex:
            case EZTalkbackHalfDuplex:
                mIsOnTalk = true;
                ezMonitorRecEntity.getEZPlayer().startVoiceTalk();
                break;
        }


    }


    private void onCapturePicBtnClick(final EzMonitorRecEntity ezMonitorRecEntity) {


        if (!SDCardUtil.isSDCardUseable()) {
            // 提示SD卡不可用
            Utils.showToast(mContext, R.string.remoteplayback_SDCard_disable_use);
            return;
        }

        if (SDCardUtil.getSDCardRemainSize() < SDCardUtil.PIC_MIN_MEM_SPACE) {
            // 提示内存不足
            Utils.showToast(mContext, R.string.remoteplayback_capture_fail_for_memory);
            return;
        }
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Bitmap bmp = ezMonitorRecEntity.getEZPlayer().capturePicture();
                if (bmp != null) {
                    try {
                        mAudioPlayUtil.playAudioFile(AudioPlayUtil.CAPTURE_SOUND);

                        // 可以采用deviceSerial+时间作为文件命名，demo中简化，只用时间命名
                        java.util.Date date = new java.util.Date();
                        final String path = Environment.getExternalStorageDirectory().getPath() + "/EZOpenSDK/CapturePicture/" + String.format("%tY", date)
                                + String.format("%tm", date) + String.format("%td", date) + "/"
                                + String.format("%tH", date) + String.format("%tM", date) + String.format("%tS", date) + String.format("%tL", date) + ".jpg";

                        if (TextUtils.isEmpty(path)) {
                            bmp.recycle();
                            bmp = null;
                            return;
                        }
                        EZUtils.saveCapturePictrue(path, bmp);


                        MediaScanner mMediaScanner = new MediaScanner(mContext);
                        mMediaScanner.scanFile(path, "jpg");
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(mContext, getResources().getString(R.string.already_saved_to_volume) + path, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (InnerException e) {
                        e.printStackTrace();
                    } finally {
                        if (bmp != null) {
                            bmp.recycle();
                            bmp = null;
                            return;
                        }
                    }
                }

            }
        });
    }


    /**
     * 判断是不是合法
     *
     * @throws
     */
    private void isValidate() {
        mLocalValidate = new LocalValidate();
        try {
            mLocalValidate.localValidatSerialNo(mSerialNoStr);
            LogUtil.infoLog(TAG, mSerialNoStr);
        } catch (BaseException e) {
            handleLocalValidateSerialNoFail(e.getErrorCode());
            LogUtil.errorLog(TAG, "searchCameraBySN-> local validate serial no fail, errCode:" + e.getErrorCode());
            return;
        }

        if (!ConnectionDetector.isNetworkAvailable(mContext)) {
            ToastUtil.show(R.string.query_camera_fail_network_exception);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("type", 1);
        bundle.putString("SerialNo", mSerialNoStr);
        bundle.putString("very_code", mSerialVeryCodeStr);
        bundle.putString(EzWifiNetConfigActivity.DEVICE_TYPE, deviceType);
        LogUtil.debugLog(TAG, "very_code:" + mSerialVeryCodeStr);
        Intent intent = new Intent(mContext, SearchEzDeviceActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void handleLocalValidateSerialNoFail(int errCode) {
        switch (errCode) {
            case ExtraException.SERIALNO_IS_NULL:
                ToastUtil.show(R.string.serial_number_is_null);
                break;
            case ExtraException.SERIALNO_IS_ILLEGAL:
                // showToast(R.string.serial_number_is_illegal);
                ToastUtil.show(R.string.unable_identify_two_dimensional_code_tip);
                break;
            default:
                ToastUtil.show(R.string.serial_number_error + "(" + errCode + ")");
                LogUtil.errorLog(TAG, "handleLocalValidateSerialNoFail-> unkown error, errCode:" + errCode);
                break;
        }
    }

    /**
     * 跳转添加探测器页面
     *
     * @see
     * @since V1.8.2
     */
    private boolean goAddProbe(String stringOrigin) {
        String[] newlineCharacterSet = {
                "\n\r", "\r\n", "\r", "\n"};

        String[] tempStr;
//        for (String sp : newlineCharacterSet) {
//
//            tempStr = stringOrigin.split(sp);
//            if (tempStr != null && tempStr.length == 5 && tempStr[4].length() == 4
//                    && DetectorType.isDetectorType(tempStr[4])) {
//                // 启动探测器关联界面
//                Intent intent = new Intent(CaptureActivity.this, AddProbeActivity.class);
//                intent.putExtra("probe_series", tempStr[1]);
//                intent.putExtra("probe_very_code", tempStr[2]);
//                intent.putExtra("probe_ex", tempStr[3]);
//                intent.putExtra("probe_type", tempStr[4]);
//                intent.putExtra("a1_device_series", mA1DeviceSeries);
//                startActivityForResult(intent, REQUEST_ADD_PROBE);
//                return true;
//            }
//        }
        return false;
    }

    @Override
    public void showDeviceInfoList(List<EZDeviceInfo> list) {
        List<MultiItemEntity> entityList = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (int i = 0; i < MAX_SIZE; i++) {
                if (i < list.size()) {
                    EzMonitorRecEntity ezMonitorRecEntity = new EzMonitorRecEntity(list.get(i));
                    entityList.add(ezMonitorRecEntity);
                    continue;
                }
                entityList.add(new EzMonitorAddEntity());
            }
        } else {
            for (int i = 0; i < MAX_SIZE; i++) {
                entityList.add(new EzMonitorAddEntity());
            }
        }
        mMonitorRecAdapter.setNewData(entityList);
    }


    @Override
    public void onDestroy() {
        mContext.unregisterReceiver(mAddSuccessReceiver);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        List<MultiItemEntity> list = mMonitorRecAdapter.getData();
        for (int i = 0; i < list.size(); i++) {
            MultiItemEntity multiItemEntity = list.get(i);
            if (multiItemEntity.getItemType() == MonitorRecAdapter.TYPE_DATA) {
                EzMonitorRecEntity ezMonitorRecEntity = (EzMonitorRecEntity) multiItemEntity;
                if (ezMonitorRecEntity.isPlay()) {
                    SurfaceView surfaceView = (SurfaceView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_sv);
                    TextView tvTip = (TextView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_tip_tv);
                    ImageView ivPlay = (ImageView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_play_iv);
                    PlayerLoadingTextView viewLoading = (PlayerLoadingTextView) mMonitorRecAdapter.getViewByPosition(mRecyclerView, i, R.id.realplay_loading);
                    EZPlayer ezPlayer = ezMonitorRecEntity.getEZPlayer();
                    ezPlayer.setSurfaceHold(surfaceView.getHolder());
                    tvTip.setVisibility(View.GONE);
                    ivPlay.setVisibility(View.GONE);
                    viewLoading.setVisibility(View.VISIBLE);
                    if (!isHide && ezMonitorRecEntity.isPlay()) {
                        ezPlayer.startRealPlay();
                    }

                }
            }


        }
    }


    @Override
    public boolean onBackPressedSupport() {
        if (mTalkPopupWindow.isShowing()) {
            MultiItemEntity entity = mMonitorRecAdapter.getItem(mEzAdapterPosition);
            if (entity.getItemType() == MonitorRecAdapter.TYPE_DATA) {
                EzMonitorRecEntity monitorRecEntity = (EzMonitorRecEntity) entity;
                closeTalkPopupWindow(true, false, monitorRecEntity);
            }
            return true;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        SecurityInfo security = new SecurityInfo();
        security.setArming(isChecked);
        THOpenSDK.getInstance().setSecurity(security);
        ToastUtil.shortShow(isChecked ? "布防成功！" : "撤防成功！");
    }
}
